package org.example.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Note;
import org.example.service.NoteService;
import org.example.utils.GetClassFields;
import org.example.utils.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 * @author 谢娅
 * @Date 2023-12-11
 */
@Slf4j
@RestController
@RequestMapping("/note")
public class NoteController {

    @Resource
    private NoteService noteService;

    @PostMapping("/save")
    public Map<String,Object> save(@RequestBody Note note) {
        if(note.getTitle() == null || "".equals(note.getTitle())){
            return Result.fileMap("笔记标题不能为空");
        }
        if(note.getContent() == null || "".equals(note.getContent())){
            return Result.fileMap("笔记内容不能为空");
        }
        Note byId = noteService.getById(note.getNoteId());
        note.setUpdatedTime(new Date());
        log.info("note:{}",note);
        boolean save;
        save = byId == null ?  noteService.updateById(note) : noteService.save(note);
        if(!save){
            return Result.fileMap("笔记保存失败");
        }
        return Result.successMap("笔记保存成功");
    }

    @GetMapping("/getCurrentNote/{userId}")
    public Map<String,Object> getCurrentNote(@PathVariable Long userId) {
        Note currentNote = noteService.getCurrentNote(userId);
        return Result.successMap(currentNote);
    }



    @DeleteMapping("/remove/{id}")
    public Map<String,Object> remove(@PathVariable Serializable id) {
        Note note = noteService.getById(id);
        if (note == null){
            return Result.fileMap("笔记不存在");
        }
        return Result.successMap("成功删除笔记");
    }

    @PostMapping("/updatePassword")
    public Map<String,Object> updatePassword(@RequestBody Map<String,Object> dataMap) {
        System.out.println("dataMap"+dataMap);
        if (dataMap == null || dataMap.isEmpty()) {
            return Result.fileMap("参数为空，更新笔记密码失败");
        }
        if(dataMap.get("note_id") == null){
            return Result.fileMap("笔记ID不能为空");
        }
        if(StringUtils.isEmpty(dataMap.get("new_password"))){
            return Result.fileMap("笔记密码不能为空");
        }

        Note note = noteService.getById(Long.valueOf(dataMap.get("note_id").toString()));

        System.out.println("note"+note);
        if(note == null){
            return Result.fileMap("笔记不存在");
        }

        if(!StringUtils.isEmpty(note.getPassword()) && dataMap.get("old_password") == null){
            return Result.fileMap("笔记已有密码，需要输入旧密码");
        }

        if(!StringUtils.isEmpty(note.getPassword()) && !note.getPassword().equals(dataMap.get("old_password"))){
            return Result.fileMap("旧密码输入错误");
        }

        note.setPassword(dataMap.get("new_password").toString());
        note.setUpdatedTime(new Date());

        boolean b = noteService.updateById(note);
        if(!b){
            return Result.fileMap("笔记密码更新失败");
        }
        return Result.successMap("成功更新笔记密码");
    }

    @PutMapping("/update")
    public Map<String,Object> update(@RequestBody Note note) {
        if(note.getNoteId() == null){
            return Result.fileMap("笔记ID不能为空");
        }
        if(StringUtils.isEmpty(note.getTitle())){
            return Result.fileMap("笔记标题不能为空");
        }
        if(StringUtils.isEmpty(note.getContent())){
            return Result.fileMap("笔记内容不能为空");
        }
        note.setUpdatedTime(new Date());
        boolean b = noteService.updateById(note);
        if(!b){
            return Result.successMap("笔记更新失败");
        }
        return Result.successMap("成功更新笔记");
    }

    @GetMapping("/list")
    public Map<String,Object> list() {
        Map<String,Object> map = new HashMap<>();
        map.put("noteList",new PageInfo<>(noteService.list()));
        return Result.successMap(map);
    }

    @GetMapping("/listByUserId")
    public Map<String,Object> listByUserId(Long userId) {
        Map<String,Object> map = new HashMap<>();
        map.put("noteList",new PageInfo<>(noteService.listByUserId(userId)));
        return Result.successMap(map);
    }

    @GetMapping("/resourceLibrary")
    public Map<String,Object> resourceLibrary(Long userId) {
        Map<String,Object> map = new HashMap<>();
        map.put("noteList",new PageInfo<>(noteService.listByUserId(userId)));
        return Result.successMap(map);
    }

    @GetMapping("/getInfo/{id}")
    public Map<String,Object> getInfo(@PathVariable Serializable id) {
        Note note = noteService.getById(id);
        if(note == null){
            return Result.fileMap("笔记不存在");
        }
        return Result.successMap(note);
    }


    @PostMapping("/search")
    public Map<String,Object> search(@RequestBody Map<String,Object> dataMap) {
        Map<String,Object> map = new HashMap<>();
        if (dataMap == null) {
            return Result.fileMap("参数为空，模糊查询失败");
        }
        String keyword = dataMap.get("keyword") == null ? null : dataMap.get("keyword").toString();
        String startTime = dataMap.get("startTime") == null ? null : dataMap.get("startTime").toString();
        String endTime = dataMap.get("endTime") == null ? null : dataMap.get("endTime").toString();
        String categoryId = dataMap.get("categoryId") == null ? null : dataMap.get("categoryId").toString();
        Long userId = Long.valueOf(dataMap.get("userId").toString());
        List<Note> noteList = noteService.search(keyword,startTime,endTime,categoryId,userId);
        map.put("noteList",noteList);
        return Result.successMap(map);
    }

    @PostMapping("/getDimQuery")
    public Map<String,Object> getDimQuery(@RequestBody(required = false) Map<String,Object> dataMap){
        PageHelper.startPage(1, 10);
        Map<String,Object> map = new HashMap<>();
        if (dataMap == null) {
            return Result.successMap(new PageInfo<>(noteService.list()));
        }
        System.out.println("dataMap"+dataMap);
        Set<String> keys = dataMap.keySet();
        List<String> domainFields = GetClassFields.getDomainFields(new Note());
        domainFields.remove(domainFields.size()-1);
        System.out.println("domainFields"+domainFields);

        List<String> snakeCaseFields = new ArrayList<>();
        for(String field:domainFields){
            String s = GetClassFields.convertCamelCaseToSnakeCase(field);
            snakeCaseFields.add(s);
        }
        System.out.println("snakeCaseFields"+snakeCaseFields);
        // 判断字段是否有这个值
        for(String key:keys){
            if(!snakeCaseFields.contains(key)){
                if(!"startTime".equals(key) && !"timeMax".equals(key)){
                    dataMap.remove(key);
                }
            }
        }
        System.out.println("dataMap2222"+dataMap);
        List<Note> dimQuery = noteService.getDimQuery(dataMap);
        map.put("dimQuery",new PageInfo<>(dimQuery));
        return Result.successMap(map);
    }
}